import {defineStore} from 'pinia';
import request from '@/utils/request';
import {ApiEndpoints} from '@/utils/api';
import router from "@/router";

interface UserState {
    accessToken: string | null;
    userId: number | null;
    loginName: string | null;
    nickName: string | null;
    avatar: string | null;
    email: string | null;
    phone: string | null;
    locked: boolean | null;
    updateTime: string | null;
}

interface LoginForm {
    account: string;
    code: string;
}

export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        accessToken: localStorage.getItem('accessToken'),
        userId: Number(localStorage.getItem('userId')) || null,
        loginName: localStorage.getItem('loginName'),
        nickName: localStorage.getItem('nickName'),
        avatar: localStorage.getItem('avatar'),
        email: localStorage.getItem('email'),
        phone: localStorage.getItem('phone'),
        locked: localStorage.getItem('locked') === 'true',
        updateTime: localStorage.getItem('updateTime'),
    }),
    actions: {
        async login(loginForm: LoginForm) {
            try {
                const response = await request.post(ApiEndpoints.USER.accountLogin, loginForm);
                const {accessToken, userId} = response.data;

                this.accessToken = accessToken;
                this.userId = userId;

                localStorage.setItem('accessToken', accessToken);
                localStorage.setItem('userId', String(userId));

                return {success: true};
            } catch (error: any) {
                return {
                    success: false,
                    message: error.response?.data?.message || '登录失败'
                };
            }
        },

        logout() {
            this.accessToken = null;
            this.userId = null;
            this.loginName = null;
            this.nickName = null;
            this.avatar = null;
            this.email = null;
            this.phone = null;
            this.locked = null;
            this.updateTime = null;
            localStorage.removeItem('accessToken');
            localStorage.removeItem('userId');
            localStorage.removeItem('loginName');
            localStorage.removeItem('nickName');
            localStorage.removeItem('avatar');
            localStorage.removeItem('email');
            localStorage.removeItem('phone');
            localStorage.removeItem('locked');
            localStorage.removeItem('updateTime');
            router.push("/login");
        },

        async getUserInfo() {
            try {
                const response = await request.get(ApiEndpoints.USER.getUserInfo);
                const {loginName, nickName, avatar, email, phone, locked, updateTime} = response.data;

                this.loginName = loginName;
                this.nickName = nickName;
                this.avatar = avatar;
                this.email = email;
                this.phone = phone;
                this.locked = locked;
                this.updateTime = updateTime;

                localStorage.setItem('loginName', loginName);
                localStorage.setItem('nickName', nickName);
                localStorage.setItem('avatar', avatar);
                localStorage.setItem('email', email);
                localStorage.setItem('phone', phone);
                localStorage.setItem('locked', String(locked));
                localStorage.setItem('updateTime', updateTime);

                return {success: true};
            } catch (error: any) {
                return {
                    success: false,
                    message: error.response?.data?.message || '获取用户信息失败'
                };
            }
        },

        async updateUserInfo(nickName: string) {
            try {
                await request.post(ApiEndpoints.USER.updateUser, {
                    id: this.userId,
                    nickName
                });
                this.nickName = nickName;
                localStorage.setItem('nickName', nickName);
                return {success: true};
            } catch (error: any) {
                return {
                    success: false,
                    message: error.response?.data?.message || '保存用户信息失败'
                };
            }
        },
    },
});